package com.share.wechat.core.service.impl;

import com.share.common.tools.ID.IDutils;
import com.share.wechat.core.entity.QuoteDetail;
import com.share.wechat.core.repository.inter.QuoteDetailRepository;
import com.share.wechat.core.service.QuoteDetailService;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.validation.constraints.NotNull;

@Service
public class QuoteDetailServiceImpl implements QuoteDetailService {
    private final Logger logger = Logger.getLogger(this.getClass());
    @Resource
    private QuoteDetailRepository quoteDetailRepository;

    @Transactional
    @Override
    public void add(QuoteDetail quoteDetail) {
        if (StringUtils.isEmpty(quoteDetail.getDetailId())) {
            logger.info("未设置detailId,请重写检查该设置" + quoteDetail);
        }

        QuoteDetail detail = quoteDetailRepository.findByDetailId(quoteDetail.getDetailId());
        if (!ObjectUtils.isEmpty(detail)) {//能够查询到 就直接更新
            detail.setDescItem(quoteDetail.getDescItem());
            detail.setPrice(quoteDetail.getPrice());
            detail.setSalesVolume(detail.getSalesVolume());
            detail.setDetailId(IDutils.getUUID());
            quoteDetailRepository.updateByDetailId(detail);
            logger.info("更新quoteDetail 成功" + detail);
            return;
        }

        logger.info("保存一个对象到数据库 基本信息为" + quoteDetail);
        quoteDetailRepository.save(quoteDetail);
    }

    @Override
    public QuoteDetail getByDetailId(String detailId) {
        if (StringUtils.isEmpty(detailId)) {
            logger.info("detailId 为空 不能再数据库查询 查询失败" + detailId);
            return null;
        }
        return quoteDetailRepository.findByDetailId(detailId);
    }

    @Transactional
    @Override
    public void updateOne(@NotNull QuoteDetail quoteDetail) {
        quoteDetailRepository.updateByDetailId(quoteDetail);
    }

}
